bool cmp(int a, int b) { return a > b; }
class Solution {
public:
    long long maxSum(vector<vector<int>>& grid, vector<int>& limits, int k) {
        long long ans = 0;
        vector<int> max;
        for (int i = 0; i < limits.size(); i++) {
            sort(grid[i].begin(), grid[i].end(), cmp);
        }
        for (int i = 0; i < limits.size(); i++) {
            for (int j = 0; j < limits[i]; j++) {
                max.push_back(grid[i][j]);
            }
        }
        sort(max.begin(), max.end(), cmp);
        for (int i = 0; i < k; i++) {
            ans += max[i];
        }
        return ans;
    }
};